import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { ActivatedRouteSnapshot, Resolve, RouterStateSnapshot } from '@angular/router';
import { BehaviorSubject, Observable } from 'rxjs';

@Injectable()
export class SettingPermitService implements Resolve<any>
{
    routeParams: any;
    permit: any[];
    onPermissionsChanged: BehaviorSubject<any>;

    /**
     * Constructor
     *
     * @param {HttpClient} _httpClient
     */
    constructor(
        private _httpClient: HttpClient
    )
    {
        // Set the defaults
        this.onPermissionsChanged = new BehaviorSubject({});
    }

    /**
     * Resolver
     *
     * @param {ActivatedRouteSnapshot} route
     * @param {RouterStateSnapshot} state
     * @returns {Observable<permit> | Promise<permit> | permit}
     */
    resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<any> | Promise<any> | any
    {
        this.routeParams = route.params;

        return new Promise((resolve, reject) => {

            Promise.all([
                this.getPermit()
            ]).then(
                () => {
                    resolve();
                },
                reject
            );
        });
    }

    /**
     * Get permissions
     *
     * @returns {Promise<permit>}
     */
    getPermit(): Promise<any>
    {
        return new Promise((resolve, reject) => {

                this._httpClient.get('http://api.catchadmin.com/permissions?page=1&limit=10')
                    .subscribe((response: any) => {
                        this.permit = response.data;
                        this.onPermissionsChanged.next(this.permit);
                        resolve(response);
                    }, reject);

        });
    }
    /**
     * Save product
     *
     * @returns {Promise<permit>}
     * @param permit
     */
    savePermit(permit): Promise<any>
    {
        return new Promise((resolve, reject) => {
            this._httpClient.post('http://127.0.0.1:8000/users/' + permit.id, permit)
                .subscribe((response: any) => {
                    resolve(response);
                }, reject);
        });
    }

    /**
     * Add product
     *
     * @returns {Promise<permit>}
     * @param permit
     */
    addPermit(permit): Promise<any>
    {
        return new Promise((resolve, reject) => {
            this._httpClient.post('http://127.0.0.1:8000/users/', permit)
                .subscribe((response: any) => {
                    resolve(response);
                }, reject);
        });
    }
    deletePermit(permit): Promise<any>{
        return new Promise((resolve, reject) => {
            this._httpClient.post('http://127.0.0.1:8000/users/', permit)
                .subscribe((response: any) => {
                    resolve(response);
                }, reject);
        });
    }
}
